﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Simple.Common.Authentication;
using System.Linq;
using System.Security.Claims;

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class CustomAuthorizeAttribute : Attribute, IAsyncAuthorizationFilter
{
    private readonly string _requiredPermission;
    private readonly CacheService _cacheService = new CacheService();

    public CustomAuthorizeAttribute(string requiredPermission)
    {
        _requiredPermission = requiredPermission;
    }

    public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
    {
        var userId = context.HttpContext.User.Claims
               .Where(c => c.Type == SimpleClaimTypes.UserId)
               .Select(c => c.Value)
               .FirstOrDefault();
        // 异步获取用户权限信息
        var userPermissions = await GetUserPermissionsFromDatabaseOrCacheAsync(userId);


        // 如果用户的权限列表中不包含所需权限，则返回未经授权的消息
        if (!userPermissions.Contains(_requiredPermission))
        {
            context.Result = new JsonResult(new { message = "Unauthorized" })
            {
                StatusCode = 403
            };
        }
    }

    // 异步从数据库或缓存中获取用户权限信息的示例方法
    private async Task<List<string>> GetUserPermissionsFromDatabaseOrCacheAsync(string username)
    {
        var result = new List<string>();
        result =await _cacheService.GetPermissionsAsync(username);
        return result;
    }
}
